<template>
  <div>
    <!--搜索表单-->
    <el-form :inline="true" class="demo-form-inline">

      <el-form-item label="学生姓名:">
        <el-input v-model="selectGrades.studentName" placeholder="学生姓名" clearable></el-input>
      </el-form-item>

      <el-form-item label="学生学号:">
        <el-input v-model="selectGrades.studentNumber" placeholder="学生学号" clearable></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>

    </el-form>

    <!--按钮-->

    <el-row>
      <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
      <el-button type="primary" plain @click="dialogVisible = true;selectStudent();selectSubject()">新增</el-button>
    </el-row>


    <!--添加数据对话框表单-->
    <el-dialog
        title="编辑成绩"
        :visible.sync="dialogVisible"
        width="30%"
        @close='closeDialog'

    >

      <el-form ref="grades" :model="grades" label-width="80px" :rules="rules">

        <el-form-item label="学生姓名">
          <el-select v-model="grades.studentName" filterable placeholder="请选择" @change="(val) => checkChange(val)">
            <el-option
                v-for="item in options"
                :key="item.studentName"
                :label="item.studentName"
                :value="item.studentName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学生学号">
          <el-select v-model="grades.studentNumber" filterable placeholder="请选择">
            <el-option
                v-for="item in row"
                :key="item.studentNumber"
                :label="item.studentNumber"
                :value="item.studentNumber">
            </el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="课程科目" prop="gradesSubjects">-->
<!--          <el-input v-model="grades.gradesSubjects" clearable></el-input>-->
<!--        </el-form-item>-->

        <el-form-item label="课程科目">
          <el-select v-model="grades.subjectName" filterable placeholder="请选择" @change="(val) => checkChange1(val)">
            <el-option
                v-for="item in row1"
                :key="item.subjectName"
                :label="item.subjectName"
                :value="item.subjectName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程成绩" prop="gradesScores">
          <el-input v-model="grades.gradesScores" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addGrades">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>


    </el-dialog>

    <!--修改数据对话框表单-->
    <el-dialog
        title="编辑成绩"
        :visible.sync="dialogVisible1"
        width="30%"
        @close='closeDialog'
    >

      <el-form ref="grades" :model="grades" label-width="80px" :rules="rules">

        <el-form-item label="学生姓名">
          <el-select disabled v-model="grades.studentName" filterable placeholder="请选择"
                     @change="(val) => checkChange(val)">
            <el-option
                v-for="item in options"
                :key="item.studentName"
                :label="item.studentName"
                :value="item.studentName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="学生学号">
          <el-select disabled v-model="grades.studentNumber" filterable placeholder="请选择">
            <el-option
                v-for="item in row"
                :key="item.studentNumber"
                :label="item.studentNumber"
                :value="item.studentNumber">
            </el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="课程科目" prop="gradesSubjects">-->
<!--          <el-input v-model="grades.gradesSubjects"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="课程科目">
          <el-select v-model="grades.subjectName" filterable placeholder="请选择" @change="(val) => checkChange1(val)">
            <el-option
                v-for="item in row1"
                :key="item.subjectName"
                :label="item.subjectName"
                :value="item.subjectName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程成绩" prop="gradesScores">
          <el-input v-model="grades.gradesScores"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="update">提交</el-button>
          <el-button @click="dialogVisible1 = false;flushed()">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!--表格-->
    <template>
      <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            fixed
            label="序号"
            align="center"
            type="index"
            width="50">
        </el-table-column>

        <el-table-column
            prop="studentName"
            label="学生姓名"
            align="center"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="studentNumber"
            label="学生学号"
            align="center"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="subjectName"
            align="center"
            label="课程科目"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="gradesScores"
            align="center"
            label="课程成绩"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="subjectCredit"
            align="center"
            label="课程学分"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="teacherName"
            align="center"
            label="授课教师"
            width="150"
        >
        </el-table-column>
        <el-table-column
            prop="teacherCollege"
            align="center"
            label="所属学院"
            width="150"
        >
        </el-table-column>

        <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="200">
          <template slot-scope="scope">
            <el-button @click="dialogVisible1 = true;pageEcho(scope.row);selectSubject()" type="primary">修改</el-button>
            <el-button type="danger" @click="dele(scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
    </el-pagination>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "GradesQuery",
  data() {
    //自定义校验分数
    var gradesScores = /^1?[1-9]?\d([.]\d)?$/
    var validateScores = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('不能为空!!'))
      }
      setTimeout(() => {
        if (!gradesScores.test(value)) {
          callback(new Error('格式有误,请输入0-100的数字'))
        } else {
          callback()
        }
      }, 100)
    }

    return {
      // 当前页码
      currentPage: 1,
      //当前页显示条数
      pageSize: 5,
      //总条数
      totalCount: 0,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 修改数据对话框是否展示标记
      dialogVisible1: false,

      // 成绩模型数据
      grades: {
        studentName: '',//学生姓名
        studentNumber: '',//学生学号
        gradesSubjects: '',//科目
        gradesId: '',//成绩id
        gradesScores: '',//课程成绩
        subjectNumber: '',//课程编号
        subjectName: '',//课程名称
        subjectCredit: '',//课程学分
        teacherName: '',//授课教师
        teacherCollege: ''//所属学院
      },
      //查询的数据
      selectGrades: {
        studentName: '',
        studentNumber: '',
      },
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      //新增中的姓名选框数据
      options: [],
      //新增中学生学号
      row: [],
      //新增中课程选框数据
      row1: [],
      //被选中的ids
      selectedIds: [],

      // 校验规则
      rules: {
        // 校验科目，主要通过validator来指定验证器名称
        // gradesSubjects: [{required: true, validator: validateSubjects, trigger: 'blur'}],
        gradesScores: [{required: true, validator: validateScores, trigger: 'blur'}]
      },
    }
  },
  mounted: function () {
    this.page();
  },
  methods: {
    //刷新页面
    flushed() {
      location.reload();
    },
    //分页查询
    page() {
      var that = this;
      this.$http.post('/grades/getPageAll2/' + this.currentPage + '/' + this.pageSize, this.selectGrades)
          .then(function (response) {
            // console.log(response)
            if (response.data.code == '200') {
              that.tableData = response.data.data.rows;
              // console.log(that.tableData);
              that.totalCount = response.data.data.totalCount;
            } else {
              that.$message.error("服务器错误，请稍后！")
            }
          }).catch(function (error) {
        console.log(error);
      })
    },
    /*删除数据*/
    dele(row) {
      var that = this;
      // console.log(row.gradesId);
      this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/grades/deleteById/" + row.gradesId)
            .then(function (response) {
              // console.log(response.data.code)
              if (response.data.code == '200') {
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新页面
                location.reload();
              } else {
                that.$message.error("删除失败，请重试！");
                location.reload();
              }
            }).catch(function (error) {
          console.log(error);
          that.$message.error("服务器错误，请重试！");
        })
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '已取消删除'
        });
        location.reload();
      });
    },
    /*批量删除*/
    deleteByIds() {
      var that = this;
      //获取当前复选框的数据
      // console.log(this.multipleSelection);
      //1.创建id数组【】，从this.multipleSelection中获取
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let selectionElement = this.multipleSelection[i];
        this.selectedIds[i] = selectionElement.gradesId;
      }
      // console.log(that.selectedIds);
      that.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        //2.发送axios请求
        this.$http.delete("/grades/deleteByIds", {data: that.selectedIds})
            .then(function (response) {
              // console.log(response.data.code);
              if (response.data.code == '200') {
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                location.reload();
              } else {
                that.$message.error("服务器错误，请重试！")
                location.reload();
              }
            }).catch(function (error) {
          console.log(error);
        });
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '已取消删除'
        });
        location.reload();
      });
    },
    /* 关闭新建清空表单 */
    closeDialog() {
      this.flushed();
    },
    //获取点击的姓名，查询学号
    checkChange(val) {
      // this.grades.studentNumber = {}
      // console.log(val) //value的值
      var that = this;
      this.$http.get("/grades/selectStudentNumber/" + val)
          .then(function (response) {
            // console.log(response.data.data);
            that.row = response.data.data;
            // console.log(that.row);
          }).catch(function (error) {
        console.log(error)
      })
    },
    //获取点击课程的数据，并将课程编号赋值
    checkChange1(val){
      console.log(val);
      var that=this;
      for (let item of that.row1) {
        if (item.subjectName==val){
          that.grades.subjectNumber=item.subjectNumber;
        }
      }

    },
    //查询所有学生
    selectStudent() {
      var that = this;
      this.$http.get("/grades/selectStudent")
          .then(function (response) {
            // console.log(response.data.data)
            that.options = response.data.data;
            // console.log(that.options);
          }).catch(function (error) {
        console.log(error)
      })
    },
    //查询所有课程
    selectSubject(){
      var that = this;
      this.$http.get("/subject/selectSubject")
          .then(function (response) {
            // console.log(response.data.data)
            that.row1 = response.data.data;
          }).catch(function (error) {
        console.log(error)
      })
    },
    //页面回显
    pageEcho(row) {
      // console.log(row);
      this.grades = row;
    },

    //修改表格中发的数据
    update() {
      // console.log(this.grades);
      var that = this;
      this.$refs.grades.validate((valid) => {
        if (valid) {
          this.$confirm('此操作将永久修改该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.$http.put("/grades/updateById", this.grades)
                .then(function (response) {
                  // console.log(response);
                  if (response.data.code == '200') {
                    that.dialogVisible1 = false;
                    that.flushed();
                    that.$message({
                      type: 'success',
                      message: '修改成功!'
                    });
                  } else {
                    that.$message.error("服务器错误，请重试！");
                    that.flushed();
                  }
                }).catch(function (error) {
              console.log(error);
            })
          }).catch(() => {
            that.$message({
              type: 'info',
              message: '已取消修改！'
            });
          });
        } else {
          this.$message.error('格式错误！')
          that.closeDialog();
        }
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    // 查询方法
    onSubmit() {
      // console.log(this.selectGrades);
      this.page();
    },
    // 添加数据
    addGrades() {
      // console.log(this.grades);
      var that = this;
      this.$refs.grades.validate((valid) => {
        if (valid) {
          this.$http.post("/grades/addGrades", this.grades)
              .then(function (response) {
                // console.log(response);
                if (response.data.code == '200') {
                  that.$message.success("添加成功！");
                  that.dialogVisible = false;
                  location.reload();
                } else {
                  that.$message.error(response.data.msg);
                  location.reload();
                }
              }).catch(function (error) {
            console.log(error);
          })
        } else {
          this.$message.error('格式错误！')
          that.closeDialog();
          return false;
        }
      })
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.page();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.page();
    },
    //隔行变色
    tableRowClassName({rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    }

  }
}
</script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>